package pri.zjy.linkedList;

import pri.zjy.linkedList.model.ListNode;

/**
 * @author zhangjy
 * @description 移除链表元素
 * @date 2025/4/28 12:04
 */
public class RemoveElements_203 {

    public static void main(String[] args) {
        RemoveElements_203 removeElements203 = new RemoveElements_203();

        ListNode two = new ListNode(2);
        ListNode one = new ListNode(1, two);
        ListNode dummyHead = new ListNode(-1, one);
        System.out.println(dummyHead);

    }

    /**
     * 个解：递归-虚拟头节点
     */
    public ListNode removeElements3(ListNode head, int val) {
       // TODO 递归

        return null;
    }

    /**
     * 个解：迭代-虚拟头节点
     * <p>
     * 思路：找到：删除；找不到：后移。从而避免漏判元素
     */
    public ListNode removeElements2(ListNode head, int val) {
        ListNode dummyHead = new ListNode(-1, head);
        ListNode cur = dummyHead;
        while (cur.next != null) {
            if (cur.next.val == val) {
                cur.next = cur.next.next;
            } else {
                cur = cur.next;
            }
        }
        return dummyHead.next;
    }

    /**
     * 错误解法
     * <p>
     * 错误原因：找到后，既删除，又后移，会导致漏判元素
     */
    public ListNode removeElements(ListNode head, int val) {
        ListNode dummyHead = new ListNode(-1, head);
        ListNode cur = dummyHead;
        while (cur.next != null) {
            if (cur.next.val == val) {
                cur.next = cur.next.next;
            }
            cur = cur.next;
        }
        return dummyHead.next;
    }

}
